<?php

namespace app\admin\controller\user;

use app\admin\controller\user\User as UserUser;
use app\common\controller\Backend;
use app\common\model\goods\Category;
use app\common\model\goods\category\Region;
use app\common\model\order\Goods;
use app\common\model\order\goods\Log as GoodsLog;
use app\common\model\order\Order;
use app\common\model\settle\Log;
use app\common\model\User;
use app\common\model\user\Group;
use app\common\model\user\Info as UserInfo;
use PDOException;
use think\Db;
use think\exception\ValidateException;

/**
 * 用户身份
 *
 * @icon fa fa-circle-o
 */
class Info extends Backend
{

    /**
     * Info模型对象
     * @var \app\common\model\user\Info
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\user\Info;
        $this->assignconfig('categoryList', Category::column('id,name'));
        $group = [0 => '无'];

        $this->assignconfig('groupList', array_merge($group, Group::column('id,name')));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index($ids = null)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user', 'group'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('user')->visible(['username']);
                $row->getRelation('group')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('user_id', $ids);

        return $this->view->fetch();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add($ids = null)
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $region = Region::where('category_id', $params['two_cate'])->where('address', $params['address'])->find();
            if (!$region) {
                exception('未授权该区域');
            }
            $info = Region::get($region['id']);
            $count = UserInfo::where('first_cate', $params['first_cate'])->where('two_cate', $params['two_cate'])->where('region_id', $region['id'])->count();
            if ($count >= $info['num']) {
                exception('该区域授权数量已达上限');
            }
            if (UserInfo::where('first_cate', $params['first_cate'])->where('two_cate', $params['two_cate'])->where('region_id', $region['id'])->where('user_id', $ids)->count()) {
                exception('用户该区域已授权');
            }

            $params['region_id'] = $region['id'];
            $params['group_id'] = 3;
            $address = explode('/', $params['address']);
            $params['province'] = $address[0];
            $params['city'] = $address[1];
            $params['area'] = $address[2];
            $params['user_id'] = $ids;
            $result = $this->model->allowField(true)->save($params);
            $user = User::get($ids);
            $user->group_id = 2;
            $user->save();
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 设置身份
     */
    public function setgroup($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $groupList = \app\admin\model\UserGroup::where('id', '>', 3)->where('id', '<', 6)->field('id,name')->select();
        $this->view->assign('groupList', $groupList);
        $this->view->assign('row', $row);
        return parent::edit($ids);
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
                $num = UserInfo::where('user_id', $item->user_id)->count();
                if (!$num) {
                    User::update(['group_id' => 1], ['id' => $item->user_id]);
                }
            }
            Db::commit();
        } catch (PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    /**
     * 结算截止时间
     */
    public function settlement($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->get($ids);
        $count = 0;
        Db::startTrans();
        try {
            $time = time();
            $order = new Order();
            if ($list->settlementtime > 0) {
                $order->whereTime('paytime', '>', $list->settlementtime);
            }
            $logs = GoodsLog::whereTime('createtime', '<', $time)->whereTime('createtime', '>', $list->settlementtime)->where('two_cate', $list->two_cate)->where('first_cate', $list->first_cate)->where('is_settle', '0')->where('user_id', $list->user_id)->select();
            $seriesmoney = $teammoney = 0;
            foreach ($logs as $k => $v) {
                $v->is_settle = 1;
                $v->settletime = $time;
                $v->save();
                if ($v->p_shareholder > 3) {
                    $teammoney += $v->money;
                }

                if ($v->p_investment == 6) {
                    $seriesmoney += $v->money;
                }
            }
            if ($teammoney <= 0 && $seriesmoney <= 0) {
                exception('结算金额为0，结算失败');
            }
            $data['user_id'] = $list->user_id;
            $data['info_id'] = $list->id;
            $data['first_cate'] = $list->first_cate;
            $data['two_cate'] = $list->two_cate;
            $data['region_id'] = $list->region_id;
            $data['shareholder'] = $list->shareholder;
            $data['investment'] = $list->investment;
            $data['money'] = $teammoney;
            $data['series_amount'] = $seriesmoney;
            $data['address'] = $list->address;
            $data['settletime'] = $time;

            Log::create($data, true);
            $list->settlementtime = $time;
            $list->save();
            Db::commit();
        } catch (PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('结算成功');
    }
}
